<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/5/31
 * Time: 15:20
 */

namespace app\api\controller\deliver\v1;


use app\api\model\Authority;
use app\api\model\Capital;
use app\api\model\Common;
use app\api\model\DetailedOptionValue;
use app\api\model\OrderModel;
use app\api\model\Products as ProductMode;
use app\api\model\ProductsSpec;
use app\api\model\ProductsV2;
use app\api\model\ProductsV2Spec;
use app\api\model\schemeMaster;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;

class Products extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
        
    }
    
    public function index()
    {
        
        $param    = Authority::param(['title', 'productsCategory', 'page', 'limit']);
        $Product1 = $this->NewIndexPublic($param);
        
        r_date($Product1, 200);
    }
    
    /*
    * 套餐公共方法
    */
    
    public function NewIndexPublic(array $param)
    {
        $Products = db('products_v2', config('database.zong'))->alias('products')
            ->join('products_v2_family', 'products.products_family_id=products_v2_family.id', 'left')
            ->join('products_v2_restricted_city products_restricted_city', 'products_restricted_city.products_id=products.id', 'left')
            ->join([\db('products_v2_tag', config('database.zong'))->group('products_id')->field('GROUP_CONCAT(products_tag ) as tag,products_id')->buildSql() => 'products_tag'], 'products_tag.products_id=products.id', 'left');
        
        if (isset($param['productsCategory']) && !empty($param['productsCategory'])) {
            $Products->where('products_v2_family.business_category_id', $param['productsCategory']);
        }
        if (isset($param['title']) && !empty($param['title'])) {
            $Products->where(['products.products_title'=>['like', "%{$param['title']}%"]]);
        }
        $Product1      = $Products->where('products.status', 1)->where(function ($quer) {
            $quer->where('products_restricted_city.city_id', config('cityId'))->whereor('products.restricted_type', 1);
        })
            ->field('concat(products.products_title,"-") as title,concat("工期",products.expected_days_min,"--",products.expected_days_max,"天") as day,products.id,tag,products.sales_method,products.products_unit_price,products_v2_family.products_family_title as groupTitle,products_v2_family.icon,products_v2_family.desc,products_v2_family.id as familyId')->page($param['page'], $param['limit'])->where('products_v2_family.delete_time',0)->where('products_v2_family.status',1)->order('products.products_sort desc')->group('products.id')->select();
        $products_spec = db('products_v2_spec', config('database.zong'))->field('products_spec_title,products_spec_price as money,products_id,products_id as only,is_required_module')->select();
        foreach ($Product1 as $k => $list) {
            $productsSpec = [];
            foreach ($products_spec as $v) {
                if ($v['products_id'] == $list['id'] && $v['is_required_module'] == 1) {
                    $v['scheme_id'] = "0";
                    $v['only']      = "" . $v['only'] . "";
                    $productsSpec[] = $v;
                }
            }
            $productsSpec[0]['money'] = array_sum(array_column($productsSpec, 'money'));
            if ($list['sales_method'] == 2) {
                $productsSpec[0]['money'] = $list['products_unit_price'];
            }
            
            $Product1[$k]['products_spec'][] = $productsSpec[0];
            
            if (count($Product1[$k]['products_spec']) == 1) {
                
                $Product1[$k]['money'] = min(array_column($Product1[$k]['products_spec'], 'money'));
            } else {
//                $Product1[$k]['money'] = min(array_column($Product1[$k]['products_spec'], 'money')) . '~~~' . max(array_column($Product1[$k]['products_spec'], 'money'));
            }
            $Product1[$k]['products_id']  = $list['id'];
            $Product1[$k]['uniqueNumber'] = date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $k;
            $Product1[$k]['tag']          = explode(',', $list['tag']);
            $Product1[$k]['img']          = db('products_v2_images', config('database.zong'))->where('products_id', $list['id'])->value('products_image');
        }
        $result   = array();
        $tageList = [];
        foreach ($Product1  as  $k => $v) {
           
            $result[$v['groupTitle']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['icon'] = $list[0]['icon'];
            $schemeTag['desc'] = $list[0]['desc'];
            $schemeTag['id'] = $list[0]['familyId'];
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        $last = array_column($tageList, 'id');
        array_multisort($last, SORT_DESC, $tageList);
        return $tageList;
    }
    /*
  * 套餐公共方法
  */
    
    public function indexPublic(array $param){
        $Products = db('products_v2', config('database.zong'))->alias('products')
            ->join('products_v2_restricted_city products_restricted_city', 'products_restricted_city.products_id=products.id', 'left')
            ->join([\db('products_v2_tag', config('database.zong'))->group('products_id')->field('GROUP_CONCAT(products_tag ) as tag,products_id')->buildSql() => 'products_tag'], 'products_tag.products_id=products.id', 'left');
        if (isset($param['productsCategory']) && !empty($param['productsCategory'])) {
            $labelList = db('business_category', config('database.zong'))->where('status', 1)->order('sort ase')->select();
            $list      = $this->get_childs($labelList, $param['productsCategory']);
            $ids        = array_column($list, 'id');
            if(empty($ids)){
                $ids=[999999999];
            };
            $products_v2_category = db('products_v2_category', config('database.zong'))->whereIn('business_category_id', implode(',',$ids).','.$param['productsCategory'])->column('products_id');
            $Products->whereIN('products.id', implode(',',$products_v2_category));
        }
        if (isset($param['productsPosition']) && !empty($param['productsPosition'])) {
            $labelList = db('business_category', config('database.zong'))->where('status', 1)->order('sort ase')->select();
            $list      = $this->get_childs($labelList, $param['productsPosition']);
            $ids        = array_column($list, 'id');
            if(empty($ids)){
                $ids=[999999999];
            }
            $products_v2_category = db('products_v2_category', config('database.zong'))->whereIn('business_category_id', implode(',',$ids).','.$param['productsPosition'])->column('products_id');
            $Products->whereIN('products.id', implode(',',$products_v2_category));
            
            
        }
        $Product1      = $Products->where('products.status', 1)->where(function ($quer){
            $quer->where('products_restricted_city.city_id', config('cityId'))->whereor('products.restricted_type',1);
        })
            
            ->field('concat(products.products_title,"-") as title,concat("工期",products.expected_days_min,"--",products.expected_days_max,"天") as day,products.id,tag,products.sales_method,products.products_unit_price')->page($param['page'], $param['limit'])->group('products.id')->select();
        $products_spec = db('products_v2_spec', config('database.zong'))->field('products_spec_title,products_spec_price as money,products_id,products_id as only,is_required_module')->select();
        foreach ($Product1 as $k => $list) {
            $productsSpec = [];
            foreach ($products_spec as $v) {
                if ($v['products_id'] == $list['id'] && $v['is_required_module'] == 1) {
                    $v['scheme_id'] = "0";
                    $v['only']      = "" . $v['only'] . "";
                    $productsSpec[] = $v;
                }
            }
            $productsSpec[0]['money']        = array_sum(array_column($productsSpec, 'money'));
            if($list['sales_method']==2){
                $productsSpec[0]['money']        =$list['products_unit_price'];
            }
            
            $Product1[$k]['products_spec'][] = $productsSpec[0];
            
            if (count($Product1[$k]['products_spec']) == 1) {
                
                $Product1[$k]['money'] = min(array_column($Product1[$k]['products_spec'], 'money'));
            } else {
//                $Product1[$k]['money'] = min(array_column($Product1[$k]['products_spec'], 'money')) . '~~~' . max(array_column($Product1[$k]['products_spec'], 'money'));
            }
            $Product1[$k]['products_id']  = $list['id'];
            $Product1[$k]['uniqueNumber'] = date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $k;
            $Product1[$k]['tag']          = explode(',', $list['tag']);
            $Product1[$k]['img']          = db('products_v2_images', config('database.zong'))->where('products_id',  $list['id'])->value('products_image');
        }
        return $Product1;
    }
    function get_childs($labelList, $id)
    {
        $ret = array();
        foreach ($labelList as $addr) {
            if ($addr['pid'] == $id) {
                array_push($ret, $addr);
                $children = self::get_childs($labelList, $addr['id']);
                if (!empty($children)) {
                    foreach ($children as $list) {
                        array_push($ret, $list);
                    }
                    
                }
            }
            
        }
        
        return $ret;
        
    }
    /*
     * 搜索中的方案标签
     */
    public function searchProgramme()
    {
        $labelList = db('business_category', config('database.zong'))->field('id,name as title')->where('pid', 0)->where('status', 1)->order('sort ase')->select();
        foreach ($labelList as $k=>$value){
            $labelList[$k]['data']= db('business_category', config('database.zong'))
                ->join('products_v2_family', 'products_v2_family.business_category_id=business_category.id', 'left')
                ->join('products_v2', 'products_v2.products_family_id=products_v2_family.id', 'left')
                ->join('products_v2_restricted_city products_restricted_city', 'products_restricted_city.products_id=products_v2.id', 'left')
                ->field('business_category.id,business_category.name as title,group_concat(products_v2.id) as productsId')
                ->where('pid', $value['id'])
               ->where('products_v2.status', 1)->where(function ($quer) {
                    $quer->where('products_restricted_city.city_id', config('cityId'))->whereor('products_v2.restricted_type', 1);
                })
                ->group('business_category.id')
                ->where('business_category.status', 1)->select();
              
            if(empty($labelList[$k]['data'])){
                unset($labelList[$k]);
            }
        }
        r_date(array_merge($labelList), 200);
    }
    
    /*
     * 搜索中的方案标签
     */
    public function searchProgrammeSubordinate()
    {
        $param     = Authority::param(['id']);
        $labelList = db('business_category', config('database.zong'))->field('id,name as title')->where('pid', $param['id'])->where('status', 1)->select();
        r_date($labelList, 200);
    }
    
    
    public
    function info(ProductsV2 $products)
    {
        $param = Authority::param(['id']);
        //'schemeProject', 'schemeProject.specsList'
        $list = $products->with('productsTag')
            ->with('productsImg')
            ->with('productsUnit')
            ->with('productsSpec')
            ->with('productsContent')
            ->where('id', $param['id'])
            ->find();
        
        foreach ($list['products_content'] as $v) {
            $listList             [] =
                [
                    'title' => $v['products_content_title'],
                    'Text' => '<style>
  img{
    width: 100% !important;
  },
</style><div style="width:100%;font-size: 20px">' . $v['products_content_value'] . '</div>',
                ];
        }
        
        $listArray['title']   = $list['products_title'];
        $listArray['content'] = $listList;
        
        $listArray['only']         = $param['id'];
        $listArray['img']          = $list['products_img'];
        $listArray['Tag']          = $list['products_tag'];
        $listArray['productPrice'] = 0;
        if ($list['sales_method'] == 2) {
            $listArray['productPrice'] = $list['products_unit_price'];
        }
        
        $productOptional = [];
        $requiredScheme  = [];
        foreach ($list['products_spec'] as $l => $i) {
            $i['unitTitle']  = $list['productsUnit'][0]['title'];
            $products_spec[] = $i;
            if ($i['is_required_module'] == 1 && $list['sales_method'] == 1) {
                $listArray['productPrice'] += $i['price'];
            }
            if ($i['is_required_module'] == 2) {
                $productOptional [] = $i;
            }
            
            if ($i['is_required_module'] == 1) {
                $requiredScheme [] = $i;
            }
            
        }
        
        if ($list['sales_method'] == 2) {
            $price = 0;
            foreach ($requiredScheme as $k => $item) {
                $requiredScheme[$k]['price'] = round($list['products_unit_price'] / count($requiredScheme), 2);
                $price                       += $requiredScheme[$k]['price'];
                if (($k + 1) == count($requiredScheme) && count($requiredScheme) != 1) {
                    $requiredScheme[$k]['price'] = round($list['products_unit_price'] - $price, 2);
                }
            }
            
        }
        $listArray['requiredScheme']  = $requiredScheme;
        $listArray['productOptional'] = $productOptional;
        
        
        r_date($listArray, 200);
        
    }
    
    public function NewProductsSchemeMasterCreationInfo(ProductsSpec $productsSpec, Common $common, DetailedOptionValue $detailedOptionValue, Capital $capital)
    {
        
        $city       = Authority::param(['productsId', 'schemeId', 'only']);
        $productsId = json_decode($city['productsId']);
        $scheme_id  = json_decode($city['schemeId']);
        $only       = json_decode($city['only']);
        if (empty($only)) {
            r_date(null, 300, '套餐参数不存在');
        }
        $rows      = $productsSpec
            ->join('products', 'products.id=products_spec.products_id', 'left')
            ->field('products.*, products_spec.id as ids,products_spec.products_id,products_spec.products_spec_title,products_spec.products_spec_price,products_spec.products_spec_original_price,products_spec.products_spec_description,products_spec.discount_rate_1,products_spec.scheme_id,products_spec.discount_rate_2,products_spec.discount_rate_1,products.products_title')
            ->whereIn('products_spec.id', $only);
        $rows      = $rows->select();
        $onlyCount = array_count_values($only);
        $rowslist  = [];
        foreach ($onlyCount as $k => $value) {
            foreach ($rows as $o => $l) {
                if ($l['ids'] == $k && $value > 1) {
                    for ($i = 2; $i <= $value; $i++) {
                        array_push($rowslist, $l);
                    }
                }
            }
        }
        $rows = array_merge($rows, $rowslist);
        
        foreach ($rows as $o) {
            $o->schemeProject;
            foreach ($o['schemeProject'] as $K => $l) {
                $l->specsList;
            }
        }

//        $productsIds = array_unique($productsId);
//        $scheme_ids  = array_unique($scheme_id);
        //array_diff_assoc：该函数比较两个（或更多个）数组的键名和键值，并返回一个差集数组，该数组包括了所有在被比较的数组（array1）中，但是不在任何其他参数数组（array2 或 array3 等等）中的键名和键值。
//        $productsIdsArray = array_diff_assoc($productsId, $productsIds);
//        $schemeIdsArray   = array_diff_assoc($scheme_id, $scheme_ids);
        
        $coutMainMoeny = 0;
        $coutMoeny     = 0;
        $beLeftOver    = 0;
        $arrayList     = [];
        $list          = [];
        $titleArray    = [];
        foreach ($rows as $k => $item) {
            $sn = date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $k;
            if (!empty($item['schemeProject'])) {
                $coutMainMoeny = 0;
                $coutMoeny     = 0;
                foreach ($item['schemeProject'] as $value) {
                    $ValueList    = $value['specsList'];
                    $ValueId      = array_column($ValueList, 'option_value_id');
                    $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $value['projectId'], $ValueId);
                    if (!$CapitalPrice['code']) {
                        r_date(null, 300, $CapitalPrice['products']);
                    }
                    $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $value['square'], $value['company'],null,0);
                    if ($value['agency'] == 0) {
                        $coutMainMoeny += $CapitalPriceSection[1];
                    }
                    if ($value['agency'] == 1) {
                        $coutMoeny += $CapitalPriceSection[1];
                    }
                    $plan_id = db('scheme_master', config('database.zong'))->where('plan_id', $value['plan_id'])->value('settlement_method');
                    if ($plan_id == 1) {
                        $value['fixedPrice'] = 0;
                    }
                    $settlement_method = empty($CapitalPrice['data']['salesCommission'])?1:$CapitalPrice['data']['salesCommission'][0]['settlement_method'];
                    $directSales=0;
                    
                       if($settlement_method==3 || $settlement_method==4){
                        $directSales=1;
                       }
                    $specs_list    = [];
                    $artificialTag = 0;
                    foreach ($value['specsList'] as $o) {
                        if ($o['condition'] == 2) {
                            $artificialTag = 1;
                        }
                        if ($o['condition'] != 2) {
                            $specs_list[] = $o;
                        }
                    }
                    unset($value['specsList']);
                    if (!empty($CapitalPrice['data']['warrantYears']) && $CapitalPrice['data']['warrantYears'] != '0.00') {
                        $isWarranty        = 1;
                        $value['warranty'] = [
                            'warrantYears' => $CapitalPrice['data']['warrantYears'],
                            'warrantyText1' => $CapitalPrice['data']['warrantyText1'],
                            'exoneration' => $CapitalPrice['data']['exoneration'],
                        ];
                    } else {
                        $value['warranty'] = null;
                        $isWarranty        = 0;
                    }
                    
                    $list[] = [
                        'allMoney' => $value['to_price'],
                        'content' => "套餐产品",
                        'products' => 1,
                        'uniqueNumber' => $sn,
                         'directSales' => $directSales,
                        'types' => 4,
                        'projectMoney' => $CapitalPriceSection[3],
                        'to_price' => $CapitalPriceSection[1],
                        'artificialTag' => $artificialTag,
                        'specsList' => $specs_list,
                        'products_id' => $item['products_id'],
                        'schemeIds' => $item['scheme_id'],
                        'isWarranty' => $isWarranty,
                        'warranty' => $value['warranty'],
                        'grouping' => $value['grouping'],
                        'projectId' => $value['projectId'],
                        'category' => $value['category'],
                        'agency' => $value['agency'],
                        'square' => $value['square'],
                        'remarks' => $value['remarks'],
                        'id' => $value['id'],
                        'fixedPrice' => $value['fixedPrice'],
                        'squareRatio' => $value['squareRatio'],
                        'company' => $value['company'],
                        'projectTitle' => $value['projectTitle'],
                    ];
                    
                }
                
            }
            
            $beLeftOver            = round($coutMainMoeny, 2) + round($coutMoeny, 2) - round($item['products_spec_price'] / 100, 2);
            $coutMainMoenyDiscount = 0;
            $coutMoenyDiscount     = 0;
            
            if ($beLeftOver > 0) {
                $coutMainMoenyDiscount = round($beLeftOver * round($item['discount_rate_1'] / 100, 2), 2);
                $coutMoenyDiscount     = round($beLeftOver * round($item['discount_rate_2'] / 100, 2), 2);
            } else {
                $beLeftOver = 0;
            }
            
            $titleArray[] = [
                'title' => $item['products_title'],
                'products_id' => $item['products_id'],
                'schemeId' => $item['scheme_id'],
                'only' => isset($item['ids']) ? $item['ids'] : 0,
                'productsSpecTitle' => $item['products_spec_title'],
                'price' => round($item['products_spec_price'] / 100, 2),
                'discount_rate_1' => round($item['discount_rate_1'] / 100, 2),
                'discount_rate_2' => round($item['discount_rate_2'] / 100, 2),
                'coutMainMoeny' => round($coutMainMoeny, 2),
                'coutMoeny' => round($coutMoeny, 2),
                'beLeftOver' => round($beLeftOver, 2),
                'coutMainMoenyDiscount' => $coutMainMoenyDiscount,
                'coutMoenyDiscount' => $coutMoenyDiscount,
                'uniqueNumber' => $sn,
            ];
            
        }
        
        $arrayList['scheme_project'] = array_merge($list);
        $result                      = array();
        if ($arrayList['scheme_project']) {
            $title = array_unique(array_column($arrayList['scheme_project'], 'grouping'));
            foreach ($title as $key => $info) {
                foreach ($arrayList['scheme_project'] as $item) {
                    if ($info == $item['grouping']) {
                        $result[$key]['title']  = $info;
                        $result[$key]['id']     = 0;
                        $result[$key]['data'][] = $item;
                    }
                    
                }
            }
            
        }
        unset($arrayList['scheme_project']);
        if (!empty($result)) {
            $arrayList['data']    = array_merge($result);
            $arrayList['product'] = array_merge($titleArray);
            
            $arrayList['idList']['schemeId']   = $scheme_id;
            $arrayList['idList']['productsId'] = $productsId;
            $arrayList['idList']['only']       = $only;
            $arrayList['total']                = round(array_sum(array_column($arrayList['product'], 'coutMainMoeny')) + array_sum(array_column($arrayList['product'], 'coutMoeny')), 2);
            $arrayList['productSummation']     = round($arrayList['total'] - array_sum(array_column($arrayList['product'], 'price')), 2);
            
            $arrayList['productsMainContract']       = round((array_sum(array_column($arrayList['product'], 'coutMainMoenyDiscount'))), 2);
            $arrayList['productsPurchasingContract'] = round((array_sum(array_column($arrayList['product'], 'coutMoenyDiscount'))), 2);
        }
        
        r_date(!empty($arrayList) ? $arrayList : null, 200);
        
    }
    
    public function ProductsSchemeMasterCreationInfo(ProductsV2 $productsV2, ProductsV2Spec $productsV2Spec, Common $common, DetailedOptionValue $detailedOptionValue, Capital $capital)
    {
            $city = Authority::param(['only']);
        $data = Request::instance()->post();
        $only = json_decode($city['only']);
        if (empty($only)) {
            r_date(null, 300, '套餐参数不存在');
        }
//        $rows      = $productsV2Spec->alias('products_spec')
//            ->join('products_v2 products', 'products.id=products_spec.products_id', 'left')
//            ->field('products.products_title,
//        products_spec.id as ids,products_spec.products_id,products_spec.products_spec_title,products_spec.products_spec_price,products_spec.products_spec_original_price,products_spec.is_required_module as required,products.products_title,products_spec_title as grouping')
//            ->whereIn('products_spec.products_id', $only);
//        $rows      = $rows->select();
        $productsList = $productsV2->whereIn('id', $only)->field('products_v2.products_title,products_v2.id,products_v2.sales_method,products_v2.initial_sales_volume,products_v2.products_unit_price,products_v2.products_unit')->select();
        
        $onlyCount = array_count_values($only);
        $rowslist  = [];
        foreach ($onlyCount as $k => $value) {
            foreach ($productsList as $o => $l) {
                if ($l['id'] == $k && $value > 1) {
                    for ($i = 2; $i <= $value; $i++) {
                        array_push($rowslist, $l);
                    }
                }
            }
        }
//        172000000011566	1709596800		172000000037643	8246.600	1	1		1709627940	0.000	8246.600	1709627895		0		1				调账
//        172000000011565	1709596800		172000000037643	-4123.300	1	1		1709627820	0.000	-4123.300	1709627812		0		1				调账
        $rows = array_merge($productsList, $rowslist);
        $envelopes_product=null;
        if(isset($data['envelopesId']) && !empty($data['envelopesId'])){
            $envelopes_product = db('envelopes_product')->where('envelopes_id', $data['envelopesId'])->whereIn('products_id',$only)->where('state', 1)->where('sales_method', 2)->field('products_unit as unit,title,products_unit_price as price,uniqueNumber')->group('products_id')->select();
        }
        foreach ($rows as $k => $o) {
            $productsV2SpecList             = $productsV2Spec->alias('products_spec')->where('products_id', $o['id'])->field('products_spec.id as ids,products_spec.products_id,products_spec.products_spec_title,products_spec.products_spec_price,products_spec.products_spec_original_price,products_spec.is_required_module as required,products_spec_title as grouping,products_spec.user_confirmation')->select();
            $rows[$k]['initialSalesVolume'] = $o['initial_sales_volume'];
            if (isset($data['number']) && $data['number'] != '') {
                $rows[$k]['initialSalesVolume'] = !empty(json_encode($data['number'], true)) ? json_decode($data['number'], true)[0] : $o['initial_sales_volume'];
            }
            if(!empty($envelopes_product)){
                $rows[$k]['initialSalesVolume'] =1;
                $rows[$k]['initial_sales_volume'] = 1;
            }
            
            $rows[$k]['data'] = $productsV2SpecList;
            
        }
        foreach ($rows as $v) {
            foreach ($v['data'] as $item) {
                $item->schemeProject;
            }
            
        }
        
        $coutMainMoeny    = 0;
        $coutMoeny        = 0;
        $beLeftOver       = 0;
        $arrayList        = [];
        $list             = [];
        $titleArray       = [];
        $productSummation = 0;
        
        
//        $sn = date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $k;
        foreach ($rows as $k => $item) {
            $sn                  = date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $k;
            $list                = [];
            $products_spec_price = 0;
            $productsSpecTitle   = [];
            $coutMainMoeny       = 0;
            $coutMoeny           = 0;
            if ($item['sales_method'] == 2) {
                $products_spec_price += round($item['initialSalesVolume'] * $item['products_unit_price'], 2);
            }
            foreach ($item['data'] as $item1) {
                if ($item['sales_method'] == 1) {
                    $products_spec_price += $item1['products_spec_price'];
                }
                
                if (!empty($item1['schemeProject'])) {
                    foreach ($item1['schemeProject'] as $k => $value) {
                        $specsList = [];
                        $initialVolume = $value['square'];
                        if ($item['sales_method'] == 2) {
                            $value['square'] = round($value['square'] + ($item['initialSalesVolume'] - 1) * $value['unitVolume'], 2);;
                         
                        }
                        if($item1['required']==2){
                            $value['square'] = 0;
                        }
                        $ValueId = json_decode($value['projectOptionValueIds'], true);;
                        $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $value['projectId'], $ValueId);
 
                        if (!$CapitalPrice['code']) {
                            r_date(null, 300, $CapitalPrice['products']);
                        }
                        if (!empty($ValueId)) {
                            $specsList = \db('detailed_option_value')->whereIn('option_value_id', implode($ValueId, ","))->field('option_value_title,option_value_id,condition,price,artificial')->select();
                        }
                        
                        $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $value['square'], $value['company'],null,0);
                        if ($item1['required'] == 1) {
                            $productsSpecTitle[] = $item1['grouping'];
                            
                            if ($value['agency'] == 0) {
                                $coutMainMoeny += $CapitalPriceSection[1];
                            }
                            if ($value['agency'] == 1) {
                                $coutMoeny += $CapitalPriceSection[1];
                            }
                        }
                       $settlement_method = empty($CapitalPrice['data']['salesCommission'])?1:$CapitalPrice['data']['salesCommission'][0]['settlement_method'];
                       $directSales=0;
                       if($settlement_method==3 || $settlement_method==4){
                        $directSales=1;
                       }
                        $value['fixedPrice'] = 0;
                        $specs_list          = [];
                        $artificialTag       = 0;
                        foreach ($specsList as $o) {
                            if ($o['condition'] == 2) {
                                $artificialTag = 1;
                            }
                            $price      = \db('detailed_option_value')->whereNUll('deleted_at')->where('is_enable', 1)->where('detailed_id', $value['projectId'])->where('condition', 2)->value('price');
                            $rangePrice = json_decode($price, true);
                            
                            if ($o['condition'] != 2) {
                                $specs_list[] = $o;
                            }
                        }
                        
                        if (!empty($CapitalPrice['data']['warrantYears']) && $CapitalPrice['data']['warrantYears'] != '0.00') {
                            $value['isWarranty'] = 1;
                            $value['warranty']   = [
                                'warrantYears' => $CapitalPrice['data']['warrantYears'],
                                'warrantyText1' => $CapitalPrice['data']['warrantyText1'],
                                'exoneration' => $CapitalPrice['data']['exoneration'],
                            ];
                        } else {
                            $value['warranty']   = null;
                            $value['isWarranty'] = 0;
                        }
                        if ($item['sales_method'] == 2) {
                            $item1['products_spec_price'] = 0;
                        }
                        $list[] = [
                            'allMoney' => $CapitalPriceSection[1],
                            'content' => "套餐产品",
                            'products' => 1,
                            'uniqueNumber' => $sn,
                            'types' => 4,
                            'directSales' => $directSales,
                            'required' => $item1['required'],
                            'projectMoney' => $CapitalPriceSection[3],
                            'initialVolume' => $initialVolume,
                            'unitVolume' => $value['unitVolume'],
                            'userConfirmation' => $item1['user_confirmation'],
                            'sales_method' => $item['sales_method'],
                            'rangePrice' => $rangePrice,
                            'artificial' => $CapitalPrice['data']['sum'],
                            'to_price' => $CapitalPriceSection[1],
                            'products_spec_price' => $item1['products_spec_price'],
                            'artificialTag' => $artificialTag,
                            'specsList' => $specs_list,
                            'products_id' => $item1['products_id'],
                            'schemeIds' => $item1['ids'],
                            'isWarranty' => $value['isWarranty'],
                            'warranty' => $value['warranty'],
                            'grouping' => $item1['grouping'],
                            'projectId' => $value['projectId'],
                            'category' => 0,
                            'agency' => $value['agency'],
                            'square' => $value['square'],
                            'remarks' => $value['remarks'],
                            'id' => $value['id'],
                            'fixedPrice' => $value['fixedPrice'],
                            'sectionTitle' => isset($CapitalPriceSection[4]) ? $CapitalPriceSection[4] : '',
                            'squareRatio' => 0,
                            'company' => $value['company'],
                            'projectTitle' => $value['projectTitle'],
                        ];
                        
                    }
                    
                }
            }
            $beLeftOver = round($coutMainMoeny, 2) + round($coutMoeny, 2) - round($products_spec_price, 2);
            if ($beLeftOver < 0) {
                $beLeftOver = 0;
            }
            $productSummation += $beLeftOver;
            $titleArray[]     = [
                'title' => $item['products_title'],
                'products_id' => $item['id'],
                'sales_method' => $item['sales_method'],
                'initialSalesVolume' => $item['initialSalesVolume'],
                'startingVolume' => $item['initial_sales_volume'],
                'productsUnitPrice' => $item['products_unit_price'],
                'unit' => \db('unit', config('database.zong'))->where('id', $item['products_unit'])->value('title'),
                'schemeId' => 0,
                'only' => $item['id'],
                'productsSpecTitle' => implode(array_unique($productsSpecTitle), ","),
                'price' => round($products_spec_price, 2),
                'discount_rate_1' => 0,
                'discount_rate_2' => 0,
                'coutMainMoeny' => round($coutMainMoeny, 2),
                'coutMoeny' => round($coutMoeny, 2),
                'beLeftOver' => round($beLeftOver, 2),
                'coutMainMoenyDiscount' => 0,
                'coutMoenyDiscount' => 0,
                'uniqueNumber' => $sn,
                'data' => $list,
            
            ];
            
        }
        $result = array();
        if ($titleArray) {
            foreach ($titleArray as $key => $info) {
                $title = array_unique(array_column($info['data'], 'grouping'));
                foreach ($title as $value) {
                    $result = [];
                    foreach ($info['data'] as $item) {
                        if ($value == $item['grouping']) {
                            $result['title']        = $value;
                            $result['id']           = 0;
                            $result['sales_method'] = $item['sales_method'];
                            $result['userConfirmation'] = $item['userConfirmation'];
                            $result['data'][]       = $item;
                        }
                    }
                    
                    $titleArray[$key]['list'][] = $result;
                }
                
            }
            $titleArray = array_merge($titleArray);
            foreach ($titleArray as $k => $o) {
                foreach ($o['list'] as $l => $v) {
                    $titleArray[$k]['list'][$l]['required']          = $v['data'][0]['required'];
                    $titleArray[$k]['list'][$l]['productsSpecPrice'] = $v['data'][0]['products_spec_price'];
                    $titleArray[$k]['list'][$l]['beLeftOver']        = 0;
                    if ($v['data'][0]['required'] == 1) {
                        if ($v['data'][0]['sales_method'] == 2) {
                            $titleArray[$k]['list'][$l]['beLeftOver'] = round(array_sum(array_column($v['data'], 'to_price')) - $o['price'], 2);
                            if(!empty($envelopes_product)) {
                                $titleArray[$k]['list'][$l]['beLeftOver'] = 0;
                            }
                        } else {
                            $titleArray[$k]['list'][$l]['beLeftOver'] = round(array_sum(array_column($v['data'], 'to_price')) - $v['data'][0]['products_spec_price'], 2);
                        }
                        
                    }
                    
                }
                
                unset($titleArray[$k]['data']);
            }
            
            $arrayList['data']                 = [];
            $arrayList['product']              = array_merge($titleArray);
            $arrayList['idList']['schemeId']   = 0;
            $arrayList['idList']['productsId'] = 0;
            $arrayList['idList']['only']       = $only;
            $arrayList['total']                = round(array_sum(array_column($arrayList['product'], 'coutMainMoeny')) + array_sum(array_column($arrayList['product'], 'coutMoeny')), 2);
            $arrayList['productSummation']     = round($productSummation, 2);
            
            $arrayList['productsMainContract']       = round((array_sum(array_column($arrayList['product'], 'coutMainMoenyDiscount'))), 2);
            $arrayList['productsPurchasingContract'] = round((array_sum(array_column($arrayList['product'], 'coutMoenyDiscount'))), 2);
        }
        
        r_date(!empty($arrayList) ? $arrayList : null, 200);
        
    }
    
    
}